#python modules
import logging
import os
import datetime

#web modules
import webapp2
import jinja2

#google modules
from google.appengine.api import users

#application modules
from config import config
from models.models import *

jinja_environment = jinja2.Environment(autoescape=True,loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../views')))

class GridHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        system_date = datetime.datetime.now().strftime("%d-%m-%Y")
        monthService = MonthService()

        mes = int(self.request.GET['mes'])
        id_year = int(config.year)

        month = monthService.get_by_number(mes,id_year,user)

        ###FIRST LOGIN WORK-AROUND###
        if (month == None):
            budgetService = BudgetService()
            budgetService.initialize(config.year,user)
            month = monthService.get_by_number(mes,id_year,user)

        if (month.expenses == None):
            expenses = []
        else:
            #expenses = month.expenses
            expenses = sorted(month.expenses, key=lambda expense: expense.description)   # sort by description


        template_values = {'username':user.nickname(),
                           'url': users.create_logout_url("/"),
                           'system_date':system_date,
                           'expenses':expenses,
                           'mes':mes,
                           'month_name':month.name,
                           'income':month.income,
                           'extra_income':month.extra_income,
                           'total_income':month.total_income(),
                           'total_expenses':month.total_expense(),
                           'balansheet':month.balansheet(),
                           'total_by_category':month.total_by_category(),
                           'total_by_type':month.total_by_type()
                          }

        # We are using the template module to output the page.
        template = jinja_environment.get_template('expense_grid.html')		
        self.response.out.write(template.render(template_values))

class EditHandler(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        system_date = datetime.datetime.now().strftime("%d-%m-%Y")
        monthService = MonthService()
        categoryService = CategoryService()

        id_expense = int(self.request.GET['id_expense'])

        categories = categoryService.get_all(user)

        if id_expense == -1:
            mes = int(self.request.GET['mes'])
            id_year = int(config.year)
            month = monthService.get_by_number(mes,id_year,user)

            expense = Expense()
            expense.month = month
        else:
            expenseService = ExpenseService()
            expense = expenseService.get_by_id(id_expense,user)

        # We are using the template module to output the page.
        template = jinja_environment.get_template('expense_edit.html')		
        template_values = {'username':user.nickname(),
                           'url': users.create_logout_url("/"),
                           'system_date':system_date,
                           'categories':categories,
                           'expense':expense}
        self.response.out.write(template.render(template_values))

    def post(self):
        logging.info("getting user...")
        user = users.get_current_user()

        expenseService = ExpenseService()
        categoryService = CategoryService()
        monthService = MonthService()

        logging.info("getting action...")
        is_save = self.request.get('btnSave')
        is_cancel = self.request.get('btnCancel')
        is_delete = self.request.get('btnDelete')
        id_expense = int(self.request.get('id_expense'))

        logging.info("Save: %s, Cancel: %s, Delete: %s, Id_expense: %s" % (is_save,is_cancel,is_delete,id_expense))
        logging.info(self.request.arguments())

        month = monthService.get_by_id(int(self.request.get('id_month')),user)
        if is_delete:
            logging.info ("Deleting Category....")
            expense = expenseService.get_by_id(int(id_expense),user)
            expenseService.delete(expense,user)
        elif is_cancel:
            pass
        else:
            logging.info ("Saving Expense....")
            if id_expense == -1:
                expense = Expense()
            else:
                expense = expenseService.get_by_id(int(id_expense),user)

            category = categoryService.get_by_id(int(self.request.get('category')),user)
            expense.description = self.request.get('description')
            expense.amount = float(self.request.get('amount'))
            expense.comment = self.request.get('comment')
            expense.category = category
            expense.month = month
            expenseService.save(expense,user)

        logging.info ("Returning....")
        self.redirect("/expense/grid?mes=" + str(month.number))
